<?php

namespace app\admin\controller;

use think\Request;
use think\Db;
use think\Loader;

class Image extends Common 
{	
	/**
	 * 图片管理主页
	 */
	public function index()
	{		
		$page      = input('?get.page') ? input('get.page') : 1;
		$order     = input('?get.order') ? input('get.order') : Null;
		$keywords  = input('?get.keywords') ? input('get.keywords') : Null;
		$pageSize  = 2;
		$totalRows = $keywords ? DB::name('goods')->where('gName', 'like', "%$keywords%")->count() : DB::name('goods')->count();
		$totalPage = ceil($totalRows/$pageSize);
		if ($keywords)
		{
			$list = DB::name('goods')
				->field('g.id, gName')
				->alias('g')
				->join('__CATE__ c','g.cId = c.id', 'LEFT')
				->where('gName', 'like', "%$keywords%")
				->order($order)
				->page($page, $pageSize)
				->select();
		} else {
			$list = DB::name('goods')
				->field('g.id, gName')
				->alias('g')
				->join('__CATE__ c','g.cId = c.id', 'LEFT')
				->order($order)
				->page($page, $pageSize)
				->select();
		}
		
		for ($i=0; $i < count($list); $i++) { 
			$list[$i]['image'] = $this->getAllImageInfoByGoods($list[$i]['id']);
		}
		$this->assign('page', $page);
		$this->assign('pageSize', $pageSize);
		$this->assign('totalPage', $totalPage);
		$this->assign('list', $list);
		return $this->fetch();
	}

	public function add($gid = '')
	{	
		$files = $request->file('image');
		$gid = ($gid != false) ? $gid : input('post.gid');
		$mark = $this->addImagesWithGoodsId($files, $gid);
		if ($mark) {
			return $this->success('图片添加成功');
		} else {
			return $this->error('图片添加失败');
		}
	}

	/**
	 * 删除图片
	 * @param  string $flag 判断是否要彻底删除原图 or 只修改数据库信息 
	 * @return mixed 
	 */
	public function delete()
	{
		$gid    = input('post.id');
		$imgIds = input('post.imgId/a');
		//默认0 暂不提供彻底删除功能
		$flag = input('post.flag') ? '1' : '0';
		//删除原图
		if ($flag == 1) {
			$path = DB::name('image')->field('imagePath')->where('id', $id)->select();
			unlink(PICTURE_ROOT_PATH . 'goods'     . DS . $path);
			unlink(PICTURE_ROOT_PATH . 'goods_50'  . DS . $path);
			unlink(PICTURE_ROOT_PATH . 'goods_150' . DS . $path);
			unlink(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
			$num = DB::name('image')->field('imagePath')->where('id', $id)->delete();
		}
		else{
			$imgIdStr = implode(',',$imgIds);
			$num = DB::name('image')->where('id', 'in', $imgIdStr)->setField('is_show', 0);
		}
		if ($num) {
			return $this->success('删除成功', '/admin/goods/index');
		}else{
			return $this->error('删除失败');
		}
	}

	public function edit()
	{

	}
	/**
	 * 将上传图片根据商品id插入数据库并生成 800*800 150*150 50*50 的缩略图
	 * 
	 * @param  obj  $images 上传图片
	 * @param  int  $gid    商品id
	 * @return bool         
	 */
	public function addImagesWithGoodsId($images, $gid)
	{
		$imagePath = array();
		/* 自动创建缩略图文件夹 */
		if (!is_dir(PICTURE_ROOT_PATH . 'goods_50' . DS . date("Ymd"))) {
			mkdir(PICTURE_ROOT_PATH . 'goods_50'  . DS . date("Ymd"));
			mkdir(PICTURE_ROOT_PATH . 'goods_150' . DS . date("Ymd"));
			mkdir(PICTURE_ROOT_PATH . 'goods_800' . DS . date("Ymd"));
		}
		/* 移动图片并生成缩略图 */
		foreach ($images as $img) {
			$info = $img->move(PICTURE_ROOT_PATH . 'goods');
			if ($info) {
				$path = $info->getSavename();
				$imagePath[] = $path;
			} else {
				return $this->error('图片上传失败');
			}
			/* 一次打开，多次处理，高效率低质量 */
			$image = \think\Image::open(PICTURE_ROOT_PATH . 'goods' . DS . $path);
			$image->thumb(800,800,\think\Image::THUMB_FILLED)->save(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
			$image->thumb(150,150,\think\Image::THUMB_FILLED)->save(PICTURE_ROOT_PATH . 'goods_150' . DS . $path);
			$image->thumb(50 ,50 ,\think\Image::THUMB_FILLED)->save(PICTURE_ROOT_PATH . 'goods_50'  . DS . $path);

			/*
			// 多次打开，多次处理，低效率高质量 
			$image = \think\Image::open(PICTURE_ROOT_PATH . 'goods' . DS . $path);
			$image->thumb(800,800,\think\Image::THUMB_FILLED)->save(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
			$image = \think\Image::open(PICTURE_ROOT_PATH . 'goods' . DS . $path);
			$image->thumb(150,150,\think\Image::THUMB_FILLED)->save(PICTURE_ROOT_PATH . 'goods_150' . DS . $path);
			$image = \think\Image::open(PICTURE_ROOT_PATH . 'goods' . DS . $path);
			$image->thumb(50 ,50 ,\think\Image::THUMB_FILLED)->save(PICTURE_ROOT_PATH . 'goods_50'  . DS . $path);
			*/
		}
		/* 构造插入数据库用数组 */
		foreach ($imagePath as $path) {
			$imageData[] = array(
						'gid' => $gid,
						'imagePath' => $path
						);
		}
		/*插入数据 */
		$mark = DB::name('image')->insertAll($imageData);
		if ($mark) {
			return true;
		} else {
			return false;
		}
	}

	public function addWatermark()
	{
		if (Request::instance()->isPost()) {
			$method = input('post.method');
			$gid    = input('post.id');
			$imgIds = input('post.imgId/a');
			switch ($method) {
				//添加文字水印
				case '1':
					// dump($_POST);
					$text = input('post.text');
					$font = input('post.font') ? input('post.font') : 'msyh';
					$size = input('post.size') ? input('post.size') : '24';
					$color = input('post.color') ? input('post.color') : '#ff0000';
					$locate = input('post.locate') ? input('post.locate') : '9';
					$offset = input('post.offset') ? input('post.offset') : '0';
					$angle = input('post.angle') ? input('post.angle') : '0';
					foreach ($imgIds as $id) {
						$this->addWaterText($id, $text, $font, $size, $color, $locate, $offset, $angle);
					}
					break;
					//添加图片水印
				case '2':
					$file = request()->file('image');
					$info = $file->move(PICTURE_ROOT_PATH . 'temp');
					$path = PICTURE_ROOT_PATH . 'temp' . DS . $info->getSavename(); 
					$opacity = input('post.opacity') ? input('post.opacity') : 80;
					$waterImg = input('post.img');
					foreach ($imgIds as $id) {
						$this->addWaterPicture($id, $path, $locate, $opacity);
					}
					break;
				default:
					# code...
					break;
			}
		}
	}

	/**
	 * 添加文字水印
	 * @param int    $id     图片id
	 * @param string $text   文字
	 * @param string $font   文字字体
	 * @param int    $size   文字大小
	 * @param string $color  文字颜色
	 * @param int    $locate 文字位置
	 * @param int    $offset 文字偏移量
	 * @param int    $angle  文字旋转角度
	 */
	public function addWaterText($id, $text, $font, $size, $color, $locate, $offset, $angle)
	{	
		$path = DB::name('image')->where('id', $id)->value('imagePath');
		// $image = \think\Image::open(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
		$image = \think\Image::open(PICTURE_ROOT_PATH . 'goods' . DS . $path);
		$image->text($text, FONT_PATH . $font . ".ttf", $size, $color, $locate, $offset, $angle)->save(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
		// $image->text($text, FONT_PATH . $font . ".ttf", $size)->save(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
	}

	public function addWaterPicture($id, $waterImgPath, $locate, $opacity)
	{	
		$path = DB::name('image')->where('id', $id)->value('imagePath');
		$image = \think\Image::open(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
		$image->water($waterImgPath, $locate, $opacity)->save(PICTURE_ROOT_PATH . 'goods_800' . DS . $path);
	}

	private function getAllImageInfoByGoods($gid)
	{
		$info = DB::name('image')
				->field('id, imagePath')
				->where('gid', $gid)
				->select();
		return $info;
	}
}
